package com.express.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.express.constants.Constants;
import com.express.entity.WxUser;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * jwt
 * @author zhoulin
 */
@Slf4j
public class JwtUtil {

    /**
     * 密钥
     */
    private static final String SECRET = "lbt@"+ Constants.EN_PHONE;
    /**
     * 过期时间
     **/
    private static final long EXPIRATION = 86400000L;//单位为毫秒 1天
    /**
     * 生成用户token,设置token超时时间
     */
    public static String createToken(WxUser user) {
        // 这里简化为直接生成JWT令牌过期时间
        Date expireDate = new Date(System.currentTimeMillis() + EXPIRATION * 15);
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        String token = JWT.create()
                .withHeader(map)// 添加头部
                //可以将基本信息放到claims中
                .withClaim("userId", user.getId())//userId
                .withClaim("pwd", user.getOpenId())//userName
                .withExpiresAt(expireDate) //超时设置,设置过期的日期
                .withIssuedAt(new Date()) //签发时间
                .sign(Algorithm.HMAC256(SECRET)); //SECRET加密
        return token;
    }

    /**
     * 校验token并解析token
     */
    public static WxUser verifyToken(String token) {
        DecodedJWT jwt = null;
        WxUser manage = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
            //decodedJWT.getClaim("属性").asString()  获取负载中的属性值
            Map<String, Claim> claims = jwt.getClaims();
            int userId = claims.get("userId").asInt();
            String pwd = claims.get("pwd").asString();
            manage = new WxUser();
            manage.setId(userId);
            manage.setOpenId(pwd);
        } catch (Exception e) {
            log.error("token解码异常",e.getMessage());
            //解码异常则抛出异常
            throw new RuntimeException("Unauthorized");
        }
        return manage;
    }

}